//
// Created by 崔世强 on 2018/3/22.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SnapKit
import UIKit
import Kingfisher
import SwiftyJSON
import Toast_Swift

class DynamicCollectionView: UICollectionView { //collection根据内容自动扩展高度
    override func layoutSubviews() {
        super.layoutSubviews()
        if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
            self.invalidateIntrinsicContentSize()
        }
    }
    
    override var intrinsicContentSize: CGSize {
        return collectionViewLayout.collectionViewContentSize
    }
}


//群聊详细信息
class GroupDetailController: ChatBaseController {
    
    var groupId: Int!
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: self.view.bounds, style: .grouped)
        table.delegate = self
        table.dataSource = self
        //        table.backgroundColor = #colorLiteral(red: 0.9372549057, green: 0.9372549057, blue: 0.9568627477, alpha: 1)
        return table
    }()
    
    
    lazy var collectionView: UICollectionView = {
        let collectionLayout = UICollectionViewFlowLayout()
        
        collectionLayout.itemSize = CGSize(width: 64, height: 80)
        //设置item内边距
        collectionLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        let collection = DynamicCollectionView(frame: CGRect.zero, collectionViewLayout: collectionLayout)
        collection.register(GroupMemberInfoCell.self, forCellWithReuseIdentifier: GroupMemberInfoCell.ID)
        //        collection.backgroundColor = .white
        collection.dataSource = self
        collection.delegate = self
        return collection
    }()
    
    
    lazy var footerView: UIView = {
        let footer = UIView()
        footer.height = 60
        let deleteButton = UIButton()
        deleteButton.setTitle("删除并退出", for: .normal)
        deleteButton.backgroundColor = .red
        deleteButton.layer.cornerRadius = 5 //设置圆角
        deleteButton.addTarget(self, action: #selector(quitGroup), for: .touchUpInside)
        footer.addSubview(deleteButton)
        deleteButton.snp.makeConstraints { make in
            make.left.equalTo(footer).offset(30)
            make.right.equalTo(footer).offset(-30)
            make.height.equalTo(40)
            make.center.equalToSuperview()
        }
        return footer
    }()
    
    lazy var deleteBtn: UIButton = {
        let deleteButton = UIButton(frame: CGRect(x: 0, y: 0, width: (UIScreen.main.bounds.width - CGFloat(30)), height: 30))
        deleteButton.setTitle("删除并退出", for: .normal)
        deleteButton.backgroundColor = .red
        deleteButton.layer.cornerRadius = 5 //设置圆角
        deleteButton.addTarget(self, action: #selector(quitGroup), for: .touchUpInside)
        return deleteButton
    }()
    
    var group: Group!
    var groupMembers = [ChatGroupMember]()
    var me: ChatGroupMember?
    
    let groupService = GroupService()
    let msgService = ChatService()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "聊天详情"
    }
    
    func loadData() {
        do {
            if let g = try GroupDao.getGroup(groupId) {
                group = g
                me = try groupService.getMyInfo(groupId)
                groupMembers = try groupService.getChatGroupMembers(groupId, limit: 43)
                
                self.view.addSubview(tableView)
                
                let count = groupMembers.count + 2
                
                let rowNum = count / 5 + (count % 5 > 0 ? 1 : 0)
                let height = 80 * rowNum + 10
                
                let collectionLayout = UICollectionViewFlowLayout()
                
                collectionLayout.itemSize = CGSize(width: (self.view.width - 30) / 5, height: 80)
                collectionLayout.minimumInteritemSpacing = 0
                collectionLayout.minimumLineSpacing = 0
                //设置item内边距
                collectionLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
                
                let collection = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: CGFloat(height)), collectionViewLayout: collectionLayout)
                collection.register(GroupMemberInfoCell.self, forCellWithReuseIdentifier: GroupMemberInfoCell.ID)
                collection.dataSource = self
                collection.delegate = self
                tableView.tableHeaderView = collection
                tableView.tableFooterView = footerView
                tableView.snp.makeConstraints { make in
                    make.edges.equalTo(self.view)
                }
            }
        } catch {
            print(error)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
        self.tableView.reloadData()
    }
}

extension GroupDetailController {
    
    fileprivate func onSuccess() {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
            self.navigationController?.popToRootViewController(animated: true)
        }
    }
    
    fileprivate func onFailure(_ msg:String) {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
            self.view.makeToast(msg, position: .center)
        }
    }
    
    
    
    @objc func quitGroup() {
        let alertController = UIAlertController(title: nil, message: "确定退出该群？", preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "确定", style: .destructive, handler: { action in
            self.view.makeModalToastActivity(.center)
            
            let userId = AppStatusManager.instance.userLoginStatus.1 ?? 0
            IM.request(.quitGroup(groupId: self.groupId, userId: userId),success: { [unowned self] (json) in
                if reqSuccess(json["code"].stringValue) {
                    do {
                        try self.groupService.quit(self.groupId)
                    } catch {
                        print(error)
                    }
                    EventProcessorWrapper().process(eventName: "sessionWillLoad", params: ["chatType": ChatType.group.rawValue])
                    self.onSuccess()
                } else {
                    let msg = json["msg"].stringValue
                    self.onFailure(msg)
                }
            }, error: { (code) in
                print("状态异常：\(code)")
                self.onFailure("服务异常，请稍后再试")
            }) { (error) in
                print(error)
                self.onFailure("服务或网络异常")
            }
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true)
    }
}

extension GroupDetailController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return groupMembers.count + 2
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GroupMemberInfoCell.ID, for: indexPath) as? GroupMemberInfoCell
        cell?.delegate = self
        if indexPath.item < groupMembers.count {
            let model = groupMembers[indexPath.item]
            
            cell?.model = model
        } else {
            if indexPath.item == groupMembers.count{
                cell?.type = .plus
                if me?.memberType == GroupMemberType.normal {
                    cell?.avatarBtn.isEnabled = false
                }
            } else {
                cell?.type = .minus
                if me?.memberType == GroupMemberType.normal {
                    cell?.avatarBtn.isEnabled = false
                }
            }
        }
        return cell!
    }
}


extension GroupDetailController: GroupMemberInfoCellDelegate {
    func avatarBtnClick(cell:GroupMemberInfoCell) {
        switch cell.type{
        case .normal:
            return
        case .plus:
            let controller = AddGroupMemberController()
            controller.groupId = self.groupId
            //                controller.groupMembers = self.groupMembers
            self.navigationController?.pushViewController(controller, animated: true)
            
        case .minus:
            let controller = DeleteGroupMemberController()
            controller.groupId = self.groupId
            //                controller.groupMembers = self.groupMembers
            self.navigationController?.pushViewController(controller, animated: true)
        }
    }
}

extension GroupDetailController: UITableViewDelegate {
    
}

extension GroupDetailController: UITableViewDataSource {
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 1:
            return 2
        case 2:
            return 2
        case 3:
            return 1
        case 4:
            return 1
        default:
            return 0
        }
    }
    
    //生成表视图单元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let collect = "collect"
        let singleLine = "singleLine"
        let twoLine = "twoLine"
        let switchCell = "switchCell"
        let defaultCell = "defaultCell"
        
        switch indexPath.section {
        case 0:  //群成员
            var cell = tableView.dequeueReusableCell(withIdentifier: collect)
            if cell == nil {
                cell = UITableViewCell(style: .value2, reuseIdentifier: collect)
            }
            let lookAllMemberBtn = UIButton()
            lookAllMemberBtn.addTarget(self, action: #selector(jumpToGroupMemberPage), for: .touchUpInside)
            lookAllMemberBtn.setTitle("查看全部群成员 >", for: .normal)
            lookAllMemberBtn.backgroundColor = .clear
            lookAllMemberBtn.setTitleColor(.gray, for: .normal)
            cell!.contentView.addSubview(lookAllMemberBtn)
            lookAllMemberBtn.snp.makeConstraints { make in
                make.center.equalToSuperview()
            }
            
            return cell!
        case 1: //群名称和公告
            switch indexPath.row {
            case 0:
                var cell = tableView.dequeueReusableCell(withIdentifier: singleLine)
                if cell == nil {
                    cell = UITableViewCell(style: .value1, reuseIdentifier: singleLine)
                    cell!.accessoryType = .disclosureIndicator
                }
                cell!.textLabel?.text = "群聊名称"
                var groupName = "未命名"
                if let name = group.name, !name.isEmpty {
                    groupName = name
                }
                cell!.detailTextLabel?.text = groupName
                return cell!
            case 1:
                var cell = tableView.dequeueReusableCell(withIdentifier: twoLine)
                if cell == nil {
                    cell = UITableViewCell(style: .subtitle, reuseIdentifier: twoLine)
                    cell!.detailTextLabel?.textColor = UIColor.gray
                    
                    cell!.accessoryType = .disclosureIndicator
                    if #available(iOS 11,*) { //因为ios11以下cell动态高度有bug，ios11显示全部内容，11以下单行显示
                        cell!.detailTextLabel?.numberOfLines = 0
                    } else {
                        cell!.detailTextLabel?.lineBreakMode = .byTruncatingTail
                    }
                }
                cell!.textLabel?.text = "群公告"
                cell!.detailTextLabel?.text = group.announcement ?? "未设置"
                return cell!
            default:
                var cell = tableView.dequeueReusableCell(withIdentifier: defaultCell)
                if cell == nil {
                    cell = UITableViewCell(style: .default, reuseIdentifier: defaultCell)
                }
                return cell!
            }
        case 2: //群设置：免打扰、置顶
            var cell = tableView.dequeueReusableCell(withIdentifier: switchCell)
            if cell == nil {
                cell = UITableViewCell(style: .default, reuseIdentifier: switchCell)
                cell!.selectionStyle = .none
                let switchBtn = UISwitch()
                switchBtn.addTarget(self, action: #selector(switchChange(_:)), for: .touchUpInside)
                cell!.accessoryView = switchBtn
            }
            let sw = cell!.accessoryView as? UISwitch
            sw?.tag = indexPath.section * 100 + indexPath.row
            //            sw?.addTarget(self, action: #selector(switchChange(_:)), for: .touchUpInside)
            switch indexPath.row {
            case 0:
                sw?.setOn(group.noDisturb, animated: false)
                cell!.textLabel?.text = "消息免打扰"
            case 1:
                sw?.setOn(group.top, animated: false)
                cell!.textLabel?.text = "置顶聊天"
            default:
                cell!.textLabel?.text = nil
            }
            return cell!
        case 3://全体禁言
            var cell = tableView.dequeueReusableCell(withIdentifier: switchCell)
            if cell == nil {
                cell = UITableViewCell(style: .default, reuseIdentifier: switchCell)
                cell!.selectionStyle = .none
                let switchBtn = UISwitch()
                cell!.accessoryView = switchBtn
            }
            let sw = cell!.accessoryView as? UISwitch
            sw?.tag = indexPath.section * 100 + indexPath.row
            sw?.addTarget(self, action: #selector(switchChange(_:)), for: .touchUpInside)
            switch indexPath.row {
            case 0:
                sw?.setOn(group.mute, animated: false)
                cell!.textLabel?.text = "全体禁言"
            default:
                cell!.textLabel?.text = nil
            }
            return cell!
        case 4: //我的群昵称
            var cell = tableView.dequeueReusableCell(withIdentifier: singleLine)
            if cell == nil {
                cell = UITableViewCell(style: .value1, reuseIdentifier: singleLine)
                cell!.accessoryType = .disclosureIndicator
            }
            switch indexPath.row {
            case 0:
                cell!.textLabel?.text = "我在本群的昵称"
                cell!.detailTextLabel?.text = (me?.nickName == nil || me?.nickName == "") ? "未设置" : me?.nickName
            default:
                cell!.textLabel?.text = nil
            }
            return cell!
        default:
            var cell = tableView.dequeueReusableCell(withIdentifier: defaultCell)
            if cell == nil {
                cell = UITableViewCell(style: .default, reuseIdentifier: defaultCell)
            }
            return cell!
        }
    }
    
    @objc func switchChange(_ switchBtn: UISwitch) {
        let tag = switchBtn.tag
        switch tag {
        case 200:
            setNoDisturb(switchBtn,on: switchBtn.isOn)
            return
        case 201:
            setTop(switchBtn,on: switchBtn.isOn)
        case 300:
            muteAll(switchBtn, on: switchBtn.isOn)
        default:
            return
        }
    }
    
    fileprivate func onNoDisturbSuccess() {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
        }
    }
    
    fileprivate func onNoDisturbFailure(_ msg: String) {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
            self.view.makeToast(msg, position: .center)
        }
    }
    
    func setNoDisturb(_ switchBtn:UISwitch, on: Bool) {
        self.view.makeModalToastActivity(.center)
        let request = on ? IMApi.noDisturb(userId: AppStatusManager.instance.userLoginStatus.1 ?? 0, sessionId: groupId, cType: ChatType.group.rawValue)
        : IMApi.cancelNoDisturb(userId: AppStatusManager.instance.userLoginStatus.1 ?? 0, sessionId: groupId, cType: ChatType.group.rawValue)
        
        IM.request(request,success: { [unowned self] (json) in
            if reqSuccess(json["code"].stringValue) {
                do {
                    try self.groupService.update(self.group.groupId, withNoDisturb: on)
                } catch {
                    print(error)
                }
                self.onNoDisturbSuccess()
            } else {
                let msg = json["msg"].stringValue
                self.onNoDisturbFailure(msg)
                DispatchQueue.main.async {
                    switchBtn.setOn(!on, animated: true)
                }
            }
        }, error: { (code) in
            print("状态异常：\(code)")
            self.onNoDisturbFailure("服务异常，请稍后再试")
            DispatchQueue.main.async {
                switchBtn.setOn(!on, animated: true)
            }
        }) { (error) in
            print(error)
            self.onNoDisturbFailure("服务或网络异常")
            DispatchQueue.main.async {
                switchBtn.setOn(!on, animated: true)
            }
        }
        
        //            imApi.request(request) { result in
        //                do {
        //                    if case let .success(response) = result {
        //                        print(String(data: response.data, encoding: .utf8))
        //                        let json = JSON(response.data)
        //                        if reqSuccess(json["data", "code"].stringValue) { //如果操作成功
        //                            try self.groupService.update(self.group.groupId, withNoDisturb: on)
        //                            self.view.hideModalToastActivity()
        //                        } else {
        //                            let msg = json["msg"].stringValue
        //                            self.onNoDisturbFailure(msg)
        //                        }
        //                    } else {
        //                        self.view.hideModalToastActivity()
        //                        self.view.makeToast("设置失败", duration: 3.0, position: .center)
        //                        switchBtn.setOn(!on, animated: true)
        //                    }
        //                } catch {
        //                    print(error)
        //                    self.view.hideModalToastActivity()
        //                    self.view.makeToast("设置失败", duration: 3.0, position: .center)
        //                    switchBtn.setOn(!on, animated: true)
        //                }
        //            }
    }
    
    fileprivate func onMuteAllSuccess() {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
        }
    }
    
    fileprivate func onMuteAllFailure(_ msg: String) {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
            self.view.makeToast(msg, position: .center)
        }
    }
    
    private func muteAll(_ switchBtn:UISwitch, on: Bool) {
        if !(me != nil && !(me!.memberType == GroupMemberType.normal)) {
            print("on:\(on)")
            self.view.makeToast("你没有权限操作", duration: 3.0, position: .center)
            //            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3 ) {
            switchBtn.setOn(!on, animated: true)
            //            }
            return
        }
        self.view.makeModalToastActivity(.center)
        let request = on ? IMApi.muteAll(groupId: groupId, userId: AppStatusManager.instance.userLoginStatus.1 ?? 0)
        : IMApi.unMuteAll(groupId: groupId, userId: AppStatusManager.instance.userLoginStatus.1 ?? 0)
        
        IM.request(request,success: { [unowned self] (json) in
            if reqSuccess(json["code"].stringValue) {
                do {
                    try self.groupService.update(self.groupId, withMuteAll: on)
                } catch {
                    print(error)
                }
                let dic: [String: Any] = ["type": (on ? NoticeType.muteAll.rawValue : NoticeType.unMuteAll.rawValue)]
                let msgJson = JSON(dic)
                self.msgService.sendNoticeMsg(msgJson.rawString() ?? "", to: self.groupId, chatType: .group)
                self.onMuteAllSuccess()
            } else {
                let msg = json["msg"].stringValue
                self.onMuteAllFailure(msg)
                switchBtn.setOn(!on, animated: true)
            }
        }, error: { (code) in
            print("状态异常：\(code)")
            self.onMuteAllFailure("服务异常，请稍后再试")
            switchBtn.setOn(!on, animated: true)
        }) { (error) in
            print(error)
            self.onMuteAllFailure("服务或网络异常")
            switchBtn.setOn(!on, animated: true)
        }
        
        //            imApi.request(request) { result in
        //                do {
        //                    if case let .success(response) = result {
        //                        print(String(data: response.data, encoding: .utf8))
        //                        let json = JSON(response.data)
        //                        if reqSuccess(json["data", "code"].stringValue) { //如果操作成功
        //                            try self.groupService.update(self.groupId, withMuteAll: on)
        //                            let dic: [String: Any] = ["type": (on ? NoticeType.muteAll.rawValue : NoticeType.unMuteAll.rawValue)]
        //                            let msgJson = JSON(dic)
        //                            try self.msgService.sendNoticeMsg(msgJson.rawString() ?? "", to: self.groupId)
        //                            self.view.hideModalToastActivity()
        //                        } else {
        //                            self.view.hideModalToastActivity()
        //                            self.view.makeToast(json["data", "msg"].stringValue, duration: 3.0, position: .center)
        //                            switchBtn.setOn(!on, animated: true)
        //                        }
        //                    } else {
        //                        self.view.hideModalToastActivity()
        //                        switchBtn.setOn(!on, animated: true)
        //                    }
        //                } catch {
        //                    print(error)
        //                    self.view.hideModalToastActivity()
        //                    switchBtn.setOn(!on, animated: true)
        //                }
        //            }
        
    }
    
    func setTop(_ switchBtn:UISwitch, on: Bool) {
        do {
            try groupService.update(group.groupId, withTop: on)
            group.top = on
        } catch {
            switchBtn.setOn(!on, animated: true)
            print(error)
        }
    }
    
    
    //获取分组数量
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    
    @objc func jumpToGroupMemberPage() {
        let groupMemberController = GroupMemberController()
        groupMemberController.groupId = groupId
        self.navigationController?.pushViewController(groupMemberController, animated: true)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0 && indexPath.row == 0 {
            jumpToGroupMemberPage()
        }
        if indexPath.section == 1 && indexPath.row == 0 {
            if !(me != nil && !(me!.memberType == GroupMemberType.normal)) {
                self.view.makeToast("你没有权限操作", duration: 3.0, position: .center)
                return
            }
            let modifyGroupNameController = ModifyGroupNameController()
            modifyGroupNameController.groupId = groupId
            modifyGroupNameController.groupName = group.name
            modifyGroupNameController.group = group
            self.navigationController?.pushViewController(modifyGroupNameController, animated: true)
        }
        
        if indexPath.section == 1 && indexPath.row == 1 {
            if !(me != nil && !(me!.memberType == GroupMemberType.normal)) {
                self.view.makeToast("你没有权限操作", duration: 3.0, position: .center)
                return
            }
            let modifyGroupAnnouncementController = ModifyGroupAnnouncementController()
            modifyGroupAnnouncementController.groupId = groupId
            modifyGroupAnnouncementController.announcement = group.announcement
            self.navigationController?.pushViewController(modifyGroupAnnouncementController, animated: true)
        }
        
        if indexPath.section == 4 && indexPath.row == 0 {
            let modifyGroupNickNameController = ModifyGroupNickNameController()
            modifyGroupNickNameController.groupId = groupId
            modifyGroupNickNameController.nickName = self.me?.nickName
            modifyGroupNickNameController.me = self.me
            self.navigationController?.pushViewController(modifyGroupNickNameController, animated: true)
        }
    }
}
